package a66weding.com.jiehuntong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeGeneralizeBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CreateZxingUtils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 这个是我的推广二维码界面
 * Created by Administrator on 2016/8/2.
 */
public class MeGeneralizeActivity extends MeBaseActivity implements View.OnClickListener , OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private TextView mGeneralizeCodeNumberTv;
    private TextView mGeneralizeWebTv;
    private TextView mNumberTv;// 我的推广
    private TextView mFriendNumberTv;// 我的好友推广
    private ImageView mGeneralizeCodeIv;
    private ImageButton mGemeralizeIBt;
    private String url;
    private RelativeLayout mGeneralizeRaly;
    private RelativeLayout myFirendGeneralizeRaly;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_generalize);
        ((GlobalApplication)getApplication()).getActivityManager().addActivity("MeGeneralizeActivity",this);

        initview();
        initdata();
    }

    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mGeneralizeCodeIv = (ImageView) findViewById(R.id.img_me_generalize_code);
        mGeneralizeCodeNumberTv = (TextView) findViewById(R.id.tv_me_generalize_number);
        mGeneralizeWebTv = (TextView) findViewById(R.id.tv_me_generalize_web);
        mNumberTv = (TextView) findViewById(R.id.tv_me_generalize_num);
        mFriendNumberTv = (TextView) findViewById(R.id.tv_my_friend_generalize_num);
        mGemeralizeIBt = (ImageButton) findViewById(R.id.ibt_me_generalize);
        mGeneralizeRaly = (RelativeLayout) findViewById(R.id.rl_me_generalize);
        myFirendGeneralizeRaly = (RelativeLayout) findViewById(R.id.rl_my_friend_generalize);

//        mGeneralizeRaly.setVisibility(View.GONE);
        myFirendGeneralizeRaly.setVisibility(View.GONE);

        mBackContentTv.setText("我的");
        mHeaderTitleTv.setText("我的推广二维码");
        mRightTitleTv.setVisibility(View.GONE);
        mGeneralizeCodeNumberTv.setText("我的邀请二维码: "+DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No());
        mGeneralizeWebTv.setText("http://j.66wedding.com?nm="+DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No());

        mBackLay.setOnClickListener(this);
        mGemeralizeIBt.setOnClickListener(this);
        mGeneralizeRaly.setOnClickListener(this);
        myFirendGeneralizeRaly.setOnClickListener(this);

        // 注意,只有在这里才能获取到控件的宽高
        mGeneralizeCodeIv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                url = "http://j.66wedding.com?nm=" +  DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No();
                //直接创建对象后传入参数,即可生成二维码
                CreateZxingUtils createZxingUtils = new CreateZxingUtils(mGeneralizeCodeIv,url,mGeneralizeCodeIv.getWidth(),mGeneralizeCodeIv.getHeight());
            }
        });

    }

    private void initdata() {
        //        取得系统日期:
        Calendar c = Calendar.getInstance();
        int mCurrentYear = c.get(Calendar.YEAR);
        int mCurrentMonth = c.get(Calendar.MONTH);
        int mCurrentDay = c.get(Calendar.DAY_OF_MONTH);

        String url= UrlDealUtil.getRealUrlNoIdApi(RequestCode.MEMBERTGLIST) +
                "&M_TG_CODE=" + DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No() +
                "&pageIndex=" + 1 +
                "&pageSize=" + 1 +
                "&orderType=" + 1 +
                "&BDate=" + (mCurrentYear-1) +"-" + (mCurrentMonth + 1) +"-" + mCurrentDay +
                "&EDate=" + mCurrentYear +"-" + (mCurrentMonth + 1) +"-" + mCurrentDay;

        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, MeGeneralizeBean.class, RequestCode.MEMBERTGLIST);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.lay_head_backlay: //点击我的，返回到上一级界面
                finish();

                break;
            case R.id.ibt_me_generalize: //点击按钮,分享出去
                showShare();

                break;
            case R.id.rl_me_generalize: //点击进入我的推广好友界面
                intent = new Intent(this,MeGeneralizeFriendActivity.class);
                intent.putExtra("generalize", "me");
                intent.putExtra("generalizeContent", mNumberTv.getText().toString());
                startActivity(intent);
                break;
            case R.id.rl_my_friend_generalize: //点击进入我的好友推广好友界面
                intent = new Intent(this,MeGeneralizeFriendActivity.class);
                intent.putExtra("generalize", "myFriend");
                intent.putExtra("generalizeContent", mFriendNumberTv.getText().toString());
                startActivity(intent);
                break;
        }
    }

    /**
     * 一键分享
     */
    private void showShare() {
        String title = "结婚通";
        String  description = "幸福从哪里开始，幸福从这里开始！";
        copyToSD(MeGeneralizeActivity.this);
//        getShareUtils();
        ShareSDK.initSDK(MeGeneralizeActivity.this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        String path = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + "pic_share_0214.jpg";
        oks.setImagePath(path);//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setText("这是结婚通应用软件,小伙伴们快来注册呀~!");
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(description);
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(MeGeneralizeActivity.this);
    }


    private static File file;
    /**把raw的图片存到SD卡上*/
    public static void copyToSD(Context context) {
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            String path = android.os.Environment.getExternalStorageDirectory()
                    .getPath();
            String dbPathAndName = path + "/" + "pic_share_0214.jpg";

            file = new File(path);

            if (file.exists() == false) {

                file.mkdir();
            }
            File dbFile = new File(dbPathAndName);
            if (!dbFile.exists()) {
                is = context.getResources().openRawResource(
                        R.raw.pic_share);
                fos = new FileOutputStream(dbFile);

                byte[] buffer = new byte[8 * 1024];// 8K
                while (is.read(buffer) > 0)// >
                {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof MeGeneralizeBean) {
            MeGeneralizeBean response = (MeGeneralizeBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    MeGeneralizeBean.TGInfoBean tGInfoBean = response.getTGInfo();
                    if(tGInfoBean != null){
                        List<MeGeneralizeBean.TGInfoBean.YJTGBean> yJTGBeans = tGInfoBean.getYJTG();
                        if(yJTGBeans!=null && yJTGBeans.size()>0){
                            MeGeneralizeBean.TGInfoBean.YJTGBean yJTGBean = yJTGBeans.get(0);
                            mGeneralizeRaly.setVisibility(View.VISIBLE);
                            mNumberTv.setText(yJTGBean.getTitle());
                        }
                        List<MeGeneralizeBean.TGInfoBean.EJTGBean> EJTGBeans = tGInfoBean.getEJTG();
                        if(EJTGBeans!=null && EJTGBeans.size()>0){
                            MeGeneralizeBean.TGInfoBean.EJTGBean EJTGBean = EJTGBeans.get(0);
                            myFirendGeneralizeRaly.setVisibility(View.VISIBLE);
                            mFriendNumberTv.setText(EJTGBean.getTitle());
                        }
                    }
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }

        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("数据请求失败");
    }
}
